<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-19 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

function validate_request($request)
{
	include ROOT_PATH.'servlet/conf/auth.conf.php';

	$auth_key = isset($request['auth_key']) ? $request['auth_key'] : '';
	$auth_code = isset($request['auth_code']) ? $request['auth_code'] : '';
	
	if($auth_key && $auth_code && isset($auth[$auth_key]))
	{	
		$validate_code = get_auth_code($auth[$auth_key]['name'], $auth[$auth_key]['key']);

		if($auth_code == $validate_code)
		{
			return true;
		}
	}
	else
	{
		request_log($request, STATUS_E, LOG_LEVEL);
		return false;
	}
}

function get_auth_code($name, $key)
{
	$cache_key = md5("get_auth_code_$name"."_$key");
	
	$result = cache_get($key);
	if($result !== false)
	{
		return $result;
	}
	
	$group_key = 'n'.'i'.'k'.'m';
	$auth_key = md5(md5($name).'-'.md5($group_key).'-'.md5($key));
	$auth_key = substr($auth_key, 0, 3).substr($auth_key, 6, 3).substr($auth_key, 12, 3).substr($auth_key, 24, 3);
	
	cache_set($key, $auth_key, 3600*24*30); // one mounth
	
	return $auth_key;
}

/**
 *
 * Write request info into log file
 * @param array $request
 * @param string $status
 * @param int $log_level: 0 - no log, 1 - access log, 2 - request log
 */
function request_log($request, $status=STATUS_S, $log_level=1)
{
	if($log_level == 0)
	{
		return '';
	}

	$date = date('Y-m-d H:i:s');

	$path = LOG_PATH.date('Y/m/d/');

	if(!file_exists($path))
	{
		mkdir($path, 0777, true);
	}
	
	include ROOT_PATH.'servlet/conf/auth.conf.php';
	$request_ip = get_client_ip();
	$auth_key = isset($request['auth_key']) ? $request['auth_key'] : '';
	$auth_name = isset($auth[$auth_key]) ? $auth[$auth_key]['name'] : 'null';
	
	$func = $request['m'].'/'.$request['a'];
	
	$end_time = microtime(true);
	$start_time = isset($request['start_time']) ? $request['start_time'] : $end_time;
	$time_use = round($end_time - $start_time, 2);
	
	$logInfo = '';
	if($log_level >= 1)
	{
		$logInfo = "Date Time: $date | IP: $request_ip | Auth: $auth_name | Time Use: $time_use | Call Function: $func";
		write_log($path.'access.log', $logInfo);
	}
	
	if($log_level >= 2)
	{		
		ob_start();
		$request = var_export($request, true);
		ob_clean();
		
		$logInfo = "Date Time: $date | Status: $status | IP: $request_ip | Auth: $auth_name | Time Use: $time_use | Call Function: $func | Request: $request \r\n";
		write_log($path.'request.log', $logInfo);
	}
}

function write_log($file, $msg)
{
	$handle = fopen($file, "a");
	$fileWrite = fwrite($handle, $msg."\n");
	fclose($handle);
}

/**
 * 
 * Show http response in json format
 * @param string $code: Message code
 * @param string $status: Response status
 */
function show_msg($request, $code, $status)
{	
	include_once ROOT_PATH .'servlet/conf/msg.conf.php';
	
	$result['version'] = API_VERSION;
	$result['status'] = $status;
	$result['message_code'] = (is_array($message) && isset($message[$code])) ? $code : '';

	$json = json_encode($result);
	
	request_log($_REQUEST, $status, LOG_LEVEL);
	
	echo $json;
	exit();
}

function show_response($requesr, $response)
{
	$json = '';
	if(is_array($response) && count($response) > 0)
	{
		$results = array_merge(array('version' => API_VERSION), $response);
		$json = @json_encode($results);
	}
	
	request_log($requesr, $response['status'], LOG_LEVEL);
	
	echo $json;
	exit();
}

/**
 * Parse request json string to array
 * @param string $json
 * @return array
 */
function parse_json($json)
{
	$result = false;

	if($json)
	{
		$json = str_replace('\n', '', $json);
		$json = stripslashes(trim($json));
		$result = @json_decode($json, true);
	}

	return $result;
}

function save_image_file($img_str, $img_type='jpeg'){
	$files = array();

	$img_type = getImageType($img_type);

	if($img_str && $img_type)
	{
		$img_str = @base64_decode($img_str);

		$im = @imagecreatefromstring($img_str);
		$valid = ($im !== false);
		@imagedestroy($im);

		// accept image size < 2M
		if($valid && strlen($img_str) < 2*1024*1024)
		{
			$fileName = @tempnam('/tmp', 'travel_info');

			@file_put_contents($fileName, $img_str);
			unset($img_str);

			@chmod($fileName, 0777);

			$files['name'] = basename($fileName).'.'.$img_type;
			$files['type'] = 'image/'.$img_type;
			$files['tmp_name'] = $fileName;
			$files['error'] = 0;
			$files['size'] = filesize($fileName);
		}
	}

	return $files;
}

/**
 *
 * 将字节流转成图片文件，并构造 $_FILES 数组
 *
 * @param $img_str string: Image string buffer
 * @param $img_type string: Image type
 *
 * @return $files array
 */
function setImgFiles($img_str, $img_type='jpeg'){
	$files = array();

	$img_type = getImageType($img_type);

	if($img_str && $img_type)
	{
		$img_str = base64_decode($img_str);

		$im = imagecreatefromstring($img_str);
		$valid = ($im !== false);
		imagedestroy($im);

		// accept image size < 2M
		if($valid && strlen($img_str) < 2*1024*1024)
		{
			$fileName = tempnam('/tmp', 'travel_info');

			file_put_contents($fileName, $img_str);
			unset($img_str);

			@chmod($fileName, 0777);

			$files['name'] = basename($fileName).'.'.$img_type;
			$files['type'] = 'image/'.$img_type;
			$files['tmp_name'] = $fileName;
			$files['error'] = 0;
			$files['size'] = filesize($fileName);
		}
	}

	return $files;
}

/**
 *
 * 检查图片类型
 *
 * @param $type string
 *
 * @return $type string: Supported image type
 */
function getImageType($type){
	$typeName = '';
	$type = strtolower($type);

	if($type)
	{
		switch($type)
		{
			case 'gif':
				$typeName = 'gif';
				break;
			case 'jpeg':
				$typeName = 'jpeg';
				break;
			case 'jpg':
				$typeName = 'jpeg';
				break;
			case 'png':
				$typeName = 'png';
				break;
			default:
				break;
		}
	}

	return $typeName;
}